package com.example.smartwaterapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.smartwaterapi.entity.User;
import com.example.smartwaterapi.service.UserService;
import com.example.smartwaterapi.service.TemplateMessageService;
import com.example.smartwaterapi.service.WaterReminderSchedulerService;
import com.example.smartwaterapi.config.WechatConfig;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage.MiniProgram;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.ArrayList;

/**
 * 定时饮水提醒服务实现类
 */
@Slf4j
@Service
public class WaterReminderSchedulerServiceImpl implements WaterReminderSchedulerService {

    @Autowired
    private UserService userService;
    
    @Autowired
    private TemplateMessageService templateMessageService;
    
    @Autowired
    private WechatConfig wechatConfig;

    /**
     * 发送早上饮水提醒 (8:30)
     */
    @Override
    @Async("scheduledTaskExecutor")
    public void sendMorningWaterReminder() {
        log.info("开始发送早上饮水提醒...");
        sendCustomWaterReminder("早安提醒", "早上好！新的一天开始了，记得喝一杯温水哦~");
    }

    /**
     * 发送中午饮水提醒 (12:00)
     */
    @Override
    @Async("scheduledTaskExecutor")
    public void sendNoonWaterReminder() {
        log.info("开始发送中午饮水提醒...");
        sendCustomWaterReminder("午间提醒", "中午好！午餐后记得补充水分，保持身体活力~");
    }

    /**
     * 发送晚上饮水提醒 (18:00)
     */
    @Override
    @Async("scheduledTaskExecutor")
    public void sendEveningWaterReminder() {
        log.info("开始发送晚上饮水提醒...");
        sendCustomWaterReminder("傍晚提醒", "傍晚好！工作一天辛苦了，记得喝杯水放松一下~");
    }

    /**
     * 发送睡前饮水提醒 (23:00)
     */
    @Override
    @Async("scheduledTaskExecutor")
    public void sendBedtimeWaterReminder() {
        log.info("开始发送睡前饮水提醒...");
        sendCustomWaterReminder("睡前提醒", "晚安！睡前喝杯温水，有助于睡眠质量哦~");
    }

    // 🔕 全局开关：是否启用主动饮水提醒
    private static final boolean ENABLE_ACTIVE_REMINDERS = false;
    
    /**
     * 发送自定义时间饮水提醒
     * 🔕 已禁用主动推送，避免打扰用户
     */
    @Override
    @Async("scheduledTaskExecutor")
    public void sendCustomWaterReminder(String eventType, String reminderText) {
        // 🔕 全局禁用主动提醒
        if (!ENABLE_ACTIVE_REMINDERS) {
            log.info("🔕 主动饮水提醒已全局禁用，跳过发送: eventType={}", eventType);
            return;
        }
        
        try {
            log.info("开始发送自定义饮水提醒: eventType={}, reminderText={}", eventType, reminderText);
            
            // 获取所有已绑定微信公众号的用户
            List<User> users = userService.list(new LambdaQueryWrapper<User>()
                    .isNotNull(User::getWxOpenid)
                    .eq(User::getStatus, 1) // 正常状态的用户
                    .eq(User::getReminderEnabled, 1)); // 开启提醒的用户
            
            if (users.isEmpty()) {
                log.info("没有找到需要发送提醒的用户");
                return;
            }
            
            log.info("找到{}个需要发送提醒的用户", users.size());
            
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            int successCount = 0;
            int failCount = 0;
            
            for (User user : users) {
                try {
                    // 构建模板数据
                    List<WxMpTemplateData> templateData = new ArrayList<>();
                    templateData.add(new WxMpTemplateData("first", reminderText, "#409EFF"));
                    templateData.add(new WxMpTemplateData("thing8", eventType, "#409EFF")); // 事件类型
                    templateData.add(new WxMpTemplateData("thing23", "智能水杯", "#333333")); // 设备名称
                    templateData.add(new WxMpTemplateData("time51", currentTime, "#333333")); // 发生时间
                    templateData.add(new WxMpTemplateData("remark", "点击查看详情，记录您的饮水情况", "#306ca5"));
                    
                    // 构建模板消息，添加跳转到小程序的链接
                    // 使用小程序路径，格式：pages/index/index
                    String miniProgramPath = "pages/index/index";
                    
                    // 构建小程序跳转信息
                    WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
                    miniProgram.setAppid(wechatConfig.getMiniAppId()); // 小程序的AppID，不是公众号的
                    miniProgram.setPagePath(miniProgramPath);
                    
                    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                            .toUser(user.getWxOpenid())
                            .templateId(wechatConfig.getTemplateId())
                            .miniProgram(miniProgram) // 使用小程序跳转
                            // 移除错误的URL跳转
                            .data(templateData)
                            .build();
                    
                    // 异步发送消息
                    templateMessageService.sendTemplateMessage(templateMessage, wechatConfig.getAppid());
                    
                    successCount++;
                    log.debug("成功发送提醒给用户: userId={}, wxOpenid={}", user.getId(), user.getWxOpenid());
                    
                } catch (Exception e) {
                    failCount++;
                    log.error("发送提醒失败: userId={}, wxOpenid={}, error={}", 
                            user.getId(), user.getWxOpenid(), e.getMessage());
                }
            }
            
            log.info("饮水提醒发送完成: 成功={}, 失败={}, 总计={}", successCount, failCount, users.size());
            
        } catch (Exception e) {
            log.error("发送饮水提醒异常", e);
        }
    }
} 